

import json
from flask import Blueprint
from flask import request
from flask import jsonify
import psycopg2.extras
from database import db_pool_singleton
from database.receive_rfid_tool_box_info_table_methods import ReceiveRfidToolBoxInfoTableMethods
from database.lend_rfid_tool_box_info_table_methods import LendRfidToolBoxInfoTableMethods
from database.tool_methods import tool_box_info # 前期测试用

rfid_tool_box_blueprint = Blueprint('rfid_tool_box', __name__)

'''-- 接收RFID工具箱信息表
CREATE TABLE IF NOT EXISTS receive_rfid_tool_box_info(
    id SERIAL PRIMARY KEY,
    mac VARCHAR(20) NOT NULL,
    task_type VARCHAR(20) NOT NULL,
    task_sn VARCHAR(50) NOT NULL,
    task_data json NOT NULL,
    create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP    
);'''
@rfid_tool_box_blueprint.route('/insert_rfid_tool_box_info', methods=['POST'])
def insert_rfid_tool_box_info():
    
    mac = request.form.get('mac')
    task_type = request.form.get('task_type')
    task_sn = request.form.get('task_sn')
    task_data = request.form.get('task_data')
    

    if not mac or not task_type or not task_sn or not task_data:
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "mac, task_type, task_sn, task_data are required",
            "resultBody": None
        }
        return jsonify(args_error)

    # Insert the data into the receive_rfid_tool_box_info table
    with db_pool_singleton.getconn() as conn:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) # cursor for executing queries
        receive_rfid_tool_box_info_table_method = ReceiveRfidToolBoxInfoTableMethods(conn, cur)
        receive_rfid_tool_box_info_table_method.insert_rfid_tool_box_info(mac, task_type, task_sn, task_data)

        insert_success = {
            "status": 1,
            "errorCode": None,
            "errorMsg": None,
            "resultBody": "Insert success"

        }
        return jsonify(insert_success)

@rfid_tool_box_blueprint.route('/select_rfid_tool_box_info', methods=['GET'])
def select_rfid_tool_box_info():
    mac = request.args.get('mac')
    
    limit_num = int(request.args.get('limit_num', 10))
    page_num = int(request.args.get('page_num', 1))

    if not mac:
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "mac is required",
            "resultBody": None
        }

        return jsonify(args_error)
    

    
    # Select the data from the receive_rfid_tool_box_info table
    with db_pool_singleton.getconn() as conn:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) # cursor for executing queries
        receive_rfid_tool_box_info_table_method = ReceiveRfidToolBoxInfoTableMethods(conn, cur)
        rfid_tool_box_info_list = receive_rfid_tool_box_info_table_method.select_rfid_tool_box_info(mac, limit_num, page_num)
        select_success = {
            "status": 1,
            "errorCode": None,
            "errorMsg": None,
            "resultBody": rfid_tool_box_info_list
        }
        return jsonify(select_success)

'''# 根据mac查询最新的RFID工具箱GPS坐标信息
    def select_rfid_tool_box_gps_info_by_mac(self, mac):
        sql = "SELECT * FROM receive_rfid_tool_box_info WHERE mac = %s ORDER BY create_time DESC LIMIT 1"
        params = (mac,)
        self.cursor.execute(sql, params)
        result = self.cursor.fetchone()

        return result'''

@rfid_tool_box_blueprint.route('/select_rfid_tool_box_gps_info_by_mac', methods=['GET'])
def select_rfid_tool_box_gps_info_by_mac():
    mac = request.args.get('mac')

    if not mac:
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "mac is required",
            "resultBody": None
        }

        return jsonify(args_error)
    
    # Select the data from the receive_rfid_tool_box_info table
    with db_pool_singleton.getconn() as conn:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) # cursor for executing queries
        receive_rfid_tool_box_info_table_method = ReceiveRfidToolBoxInfoTableMethods(conn, cur)
        rfid_tool_box_gps_info = receive_rfid_tool_box_info_table_method.select_rfid_tool_box_gps_info_by_mac(mac)
        select_success = {
            "status": 1,
            "errorCode": None,
            "errorMsg": None,
            "resultBody": rfid_tool_box_gps_info
        }
        return jsonify(select_success)
    
@rfid_tool_box_blueprint.route('/get_task_type_is_inventory_data_by_mac_last_time', methods=['GET'])
def get_task_type_is_inventory_data_by_mac_last_time():
    mac = request.args.get('mac', "01")

    if not mac:
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "mac is required",
            "resultBody": None
        }


        return jsonify(args_error)
    
    # Select the data from the receive_rfid_tool_box_info table
    with db_pool_singleton.getconn() as conn:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) # cursor for executing queries
        receive_rfid_tool_box_info_table_method = ReceiveRfidToolBoxInfoTableMethods(conn, cur)
        task_type_is_inventory_data = receive_rfid_tool_box_info_table_method.get_task_type_is_inventory_data_by_mac_last_time(mac)
        if task_type_is_inventory_data == "数据包数量不匹配":
            err = {
                "status": -1,
                "errorCode": 1005,
                "errorMsg": "数据包数量不匹配",
                "resultBody": None

            }
            return jsonify(err)
        select_success = {
            "status": 1,
            "errorCode": None,
            "errorMsg": None,
            "resultBody": task_type_is_inventory_data
        }
        return jsonify(select_success)

@rfid_tool_box_blueprint.route('/get_tool_box_list', methods=['GET']) # 测试用
def get_tool_box_list():
    
    with db_pool_singleton.getconn() as conn:
        cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) # cursor for executing queries
        receive_rfid_tool_box_info_table_method = ReceiveRfidToolBoxInfoTableMethods(conn, cur)
        gps_info = receive_rfid_tool_box_info_table_method.get_task_type_is_GPS_by_mac_last(mac="01")
        
        if not gps_info:
            gps_info = None
            status = "离线"

        else:
            gps_info = gps_info["task_data"]
            status = "在线"

        
        # 获取借用状态
        
        lend_rfid_tool_box_info_table_method = LendRfidToolBoxInfoTableMethods(conn, cur)
        lend_info = lend_rfid_tool_box_info_table_method.get_lend_rfid_tool_box_info_status_by_tool_box_mac("01")
        
        
        if not lend_info:
            lend_status = "return"
        else:
            lend_status = lend_info["status"]

    result = {
        "status": 1,
        "errorCode": None,
        "errorMsg": None,
        "resultBody":  [
            {
                "mac": "00:00:00:00:00:01",
                "model": "BNZ-001",
                "lend_status": lend_status,
                "tool_count": 20,
                "tool_img_url": None,
                "GPS_info": gps_info
            }
        ]
        
    }

    return jsonify(result)

# 设备绑定的工具列表
@rfid_tool_box_blueprint.route('/get_tool_list_by_mac', methods=['GET'])
def get_tool_list_by_mac():
    mac = request.args.get('mac', "01")


    if not mac:
        args_error = {
            "status": -1,
            "errorCode": 1001,
            "errorMsg": "mac is required",
            "resultBody": None
        }

        return jsonify(args_error)
    
    return {
        "status": 1,    
        "errorCode": None,
        "errorMsg": None,
        "resultBody": tool_box_info
    }
    
    